﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Payton.WP7.Common.Model;
using System.Threading;
using System.Windows.Media.Imaging;
using Payton.WP7.Common;
using System.IO;
using System.Collections.ObjectModel;
using Payton.WP7.Common.Interface;
using System.Collections.Generic;
using Payton.WP7.Converter;
using Microsoft.Practices.Prism.Commands;
using System.Linq;

namespace Payton.WP7.ViewModel
{
    public class StatusDetailViewModel : SNSStatusViewModel
    {
        #region field

        private int pagecount = 10;
        private ObservableCollection<SNSStatusViewModel> comments = new ObservableCollection<SNSStatusViewModel>();
        private IStatusService _statusSvc;


        #endregion

        #region Properties

        public Action<SNSStatusViewModel> OnRefreshed { get; set; }

        bool loaded = true;

        public bool Loaded
        {
            get { return loaded; }
            set { loaded = value; RaisePropertyChanged(() => Loaded); }
        }

        int pivotSelectedIndex;

        public int PivotSelectedIndex
        {
            get
            {
                return pivotSelectedIndex;
            }
            set
            {
                pivotSelectedIndex = value;
                RaisePropertyChanged(() => PivotSelectedIndex);
                //PerformGetItems();
            }
        }

        string repostText;

        public string RepostText
        {
            get
            {
                return repostText;
            }
            set
            {
                repostText = value;
                RaisePropertyChanged(() => RepostText);
            }
        }

        string replayText;

        public string CommentText
        {
            get
            {
                return replayText;
            }
            set
            {
                replayText = value;
                RaisePropertyChanged(() => CommentText);
            }
        }

        bool HasComments
        {
            get
            {
                return comments.Count > 0;
            }
            set
            {
                RaisePropertyChanged(() => HasComments);
            }
        }

        private SNSStatusViewModel defaultItem;

        public SNSStatusViewModel DefaultItem
        {
            get
            {
                return defaultItem;
            }
            set
            {
                defaultItem = value;
                RaisePropertyChanged(() => DefaultItem);
            }
        }

        public ObservableCollection<SNSStatusViewModel> Comments
        {
            get { return comments; }
            set
            {
                comments = value;
                RaisePropertyChanged(() => Comments);
            }
        }

        public DelegateCommand Repost { get; set; }
        public DelegateCommand Replay { get; set; }
        public DelegateCommand MoreComments { get; set; }
        public DelegateCommand RefreshComments { get; set; }

        #endregion

        #region ctor

        public StatusDetailViewModel(SNSStatus status)
        {
            Item = status;

            Initialize();

            LoadData();

            GetImages(status);

            Repost = new DelegateCommand(RepostMethod, () => { return !Loading; });
            Replay = new DelegateCommand(ReplayMethod, () => { return !Loading; });
            MoreComments = new DelegateCommand(MoreCommentsMethod, () => { return !Loading; });
            RefreshComments = new DelegateCommand(RefreshCommentsMethod, () => { return !Loading; });
            if (Item.RetweetedStatus != null)
            {
                RepostText = "||@" + Item.User.AccountName + " ";
                CommentText = "@" + Item.User.AccountName + " ";
            }
        }
        #endregion

        protected override void Initialize()
        {
            //base.Initialize();
            _statusSvc = PhoneApplicationController.Current.Container.Resolve<IStatusService>(Item.Provider.ToString());
            _statusSvc.Account = Item.Account;
        }

        private void RepostMethod()
        {
            if (string.IsNullOrEmpty(RepostText))
                return;

            Loading = true;
            var request = new SNSRequest() { Type = SNSType.RepostStatus, WebMethod = Hammock.Web.WebMethod.Post };

            //for sina
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ID, Item.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.STATUS_TEXT, RepostText));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.IS_COMMENT, "0"));//SINA|是否在转发的同时发表评论。0表示不发表评论，1表示发表评论给当前微博，2表示发表评论给原微博，3是1、2都发表。默认为0。 

            //For tencent
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.CONTENT, RepostText));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.CLIENT_IP, "127.0.0.1"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REID, Item.Id.ToString()));

            _statusSvc.AddComment(request, (data, result) =>
            {
                if (!result.IsSuccess)
                {
                    //{"request":"/statuses/repost.json","error_code":"400","error":"40025:Error: repeated weibo text!"}
                    //{"request":"/statuses/repost.json","error_code":"400","error":"40028:不要太贪心哦！你已经发过一次啦。"}
                    string message = result.Message;
                    if (message.Contains("repeated") || message.Contains("发过一次"))
                    {
                        message = AppResx.StatusrRepeatedText;
                    } 
                    //fixed by Kenny 2011-09-01 00:31:00
                    ExecuteOnUIThread(() => { MessageBox.Show(message); Loading = false; });
                    return;
                }
                ExecuteOnUIThread(() =>
                {
                    if (data != null)
                    {
                        MessageBox.Show(AppResx.RepostSuccessText);
                    }

                    Loading = false;
                    RepostText = string.Empty;
                });
            });
        }

        private void ReplayMethod()
        {
            if (string.IsNullOrEmpty(CommentText))
                return;

            Loading = true;
            var request = new SNSRequest() { Type = SNSType.AddComment, WebMethod = Hammock.Web.WebMethod.Post };

            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ID, Item.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COMMENT, CommentText));
            //request.Parameters.Add(new SNSParameter(SNSParametersConstants.CID, "0"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.WITHOUT_MENTION, "0"));//SINA|1：回复中不自动加入“回复@用户名”，0：回复中自动加入“回复@用户名”.默认为0. 
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COMMENT_ORI, "0"));//SINA|当评论一条转发微博时，是否评论给原微博。0:不评论给原微博。1：评论给原微博。默认0. 


            //For tencent
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.CONTENT, CommentText));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.CLIENT_IP, "127.0.0.1"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REID, Item.Id.ToString()));
            _statusSvc.AddComment(request, (data, result) =>
            {
                if (!result.IsSuccess)
                {
                    ExecuteOnUIThread(() => { MessageBox.Show(result.Message); Loading = false; });
                    return;
                }
                if (data != null)
                {
                    ExecuteOnUIThread(() =>
                    {
                        var viewmodel = new SNSStatusViewModel(data);
                        Comments.Insert(0, viewmodel);
                        Loading = false;
                        CommentText = string.Empty;

                        if (OnRefreshed != null)
                        {
                            ExecuteOnUIThread(() =>
                            {
                                OnRefreshed(viewmodel);
                            });
                        }
                    });
                }
            });
        }

        private void MoreCommentsMethod()
        {
            SNSRequest request = null;
            string pageflag = "1";
            long pagetime = 0;
            long maxid = 0;

            request = new SNSRequest() { Type = SNSType.CommentsByID };
            GetPagingInfo(Comments, ref pagetime, ref maxid, false);

            //sina
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ID, Item.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COUNT, pagecount + ""));

            //tencent
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.FLAG, "1"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ROOTID, Item.Id.ToString()));

            if (maxid != 0)
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.MAX_ID, (maxid > 0 ? (maxid - 1) : 0) + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_FLAG, pageflag));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_TIME, pagetime + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.TWITTERID, maxid + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REQ_NUM, pagecount + ""));
            _statusSvc.GetTimeline(request, (data, result) =>
            {
                if (!result.IsSuccess)
                {
                    ExecuteOnUIThread(() => { Loading = false; MessageBox.Show(result.Message); });
                    return;
                }

                PopupComments(Comments, data, false);

                ExecuteOnUIThread(() =>
                {
                    if (OnNextPagePerformed != null)
                    {
                        OnNextPagePerformed();
                    }
                });

            });

            Loading = true;
        }

        private void RefreshCommentsMethod()
        {
            SNSRequest request = null;
            string pageflag = "2";
            long pagetime = 0;
            long sinceid = 0;

            request = new SNSRequest() { Type = SNSType.CommentsByID };
            GetPagingInfo(Comments, ref pagetime, ref sinceid, true);

            //sina
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ID, Item.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COUNT, pagecount + ""));

            //tencent
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.FLAG, "1"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ROOTID, Item.Id.ToString()));

            if (sinceid != 0)
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.SINCE_ID, (sinceid + 1) + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_FLAG, pageflag));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_TIME, pagetime + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.TWITTERID, sinceid + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REQ_NUM, pagecount + ""));

            _statusSvc.GetTimeline(request, (data, result) =>
            {
                if (!result.IsSuccess)
                {
                    ExecuteOnUIThread(() => { Loading = false; });
                    return;
                }

                PopupComments(Comments, data, false);

                if (OnRefreshed != null && data != null && data.Count > 0)
                {
                    ExecuteOnUIThread(() =>
                    {
                        OnRefreshed(Comments[0]);
                    });
                }
            });

            Loading = true;
        }

        private void GetImages(SNSStatus status)
        {
            if (!string.IsNullOrEmpty(Item.BmiddlePic))
            {
                Image = new Uri(status.BmiddlePic, UriKind.Absolute);
            }
            else if (!string.IsNullOrEmpty(Item.ThumbnailPic))
            {
                Image = new Uri(Item.ThumbnailPic, UriKind.Absolute);
            }

            if (Item.RetweetedStatus != null && !string.IsNullOrEmpty(Item.RetweetedStatus.BmiddlePic))
            {
                RetweetImage = new Uri(Item.RetweetedStatus.BmiddlePic, UriKind.Absolute);
            }
            else if (Item.RetweetedStatus != null && !string.IsNullOrEmpty(Item.RetweetedStatus.ThumbnailPic))
            {
                RetweetImage = new Uri(Item.RetweetedStatus.ThumbnailPic, UriKind.Absolute);
            }

            if (Item.User != null && !string.IsNullOrEmpty(Item.User.ProfileImageUrl))
            {
                FaceImageUri = new Uri(Item.User.ProfileImageUrl, UriKind.Absolute);
            }
        }

        protected override void LoadData()
        {
            //base.LoadData();
            var request = new SNSRequest() { Type = SNSType.CommentsByID };

            //sina
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ID, Item.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COUNT, 10 + ""));

            //tencent
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.FLAG, "1"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ROOTID, Item.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_FLAG, "0"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_TIME, "0"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REQ_NUM, 10 + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.TWITTERID, "0"));

            _statusSvc.GetTimeline(request, (data, result) =>
            {
                if (!result.IsSuccess)
                {
                    //ExecuteOnUIThread(() => {MessageBox.Show(result.Message); Loading = false;});
                    //no comment;
                    return;
                }
                PopupComments(Comments, data, false);
                ExecuteOnUIThread(() =>
                {
                    if (OnNextPagePerformed != null)
                    {
                        OnNextPagePerformed();
                    }
                });
            });
        }

        private void PopupComments(ObservableCollection<SNSStatusViewModel> items, IList<SNSStatus> data, bool isInsert)
        {
            if (data != null && data.Count > 0)
            {
                foreach (var status in data)
                {
                    var viewmodel = new SNSStatusViewModel(status);
                    if (isInsert)
                    {
                        ExecuteOnUIThread(() =>
                        {
                            items.Insert(0, viewmodel);
                        });
                    }
                    else
                    {
                        ExecuteOnUIThread(() =>
                        {
                            items.Add(viewmodel);
                        });

                        //Items.Add(new SNSStatusViewModel(status_copy));
                    }
                    Thread.Sleep(100);
                }
            }
            Thread.Sleep(400);
            ExecuteOnUIThread(() =>
            {
                Loading = false;
                HasComments = HasComments;
                //if (OnRefreshed != null && data.Count > 0)
                //{
                //    OnRefreshed(items[0]);
                //}
            });
        }

        private static void GetPagingInfo(IEnumerable<SNSStatusViewModel> items, ref long pagetime, ref long id, bool isRefresh)
        {
            if (isRefresh)
            {
                var firstItemTencent = items.FirstOrDefault(item => item.Item.Account.ServiceProvider == SNSProviderType.Tencent);
                if (firstItemTencent != null)
                {
                    pagetime = firstItemTencent.Item.Timestamp;
                }

                //for sina

                var firstItem = items.FirstOrDefault();
                if (firstItem != null)
                {
                    id = firstItem.Item.Id;
                }
            }
            else
            {
                var firstItemTencent = items.LastOrDefault(item => item.Item.Account.ServiceProvider == SNSProviderType.Tencent);
                if (firstItemTencent != null)
                {
                    pagetime = firstItemTencent.Item.Timestamp;
                }

                //for sina

                var firstItem = items.LastOrDefault();
                if (firstItem != null)
                {
                    id = firstItem.Item.Id;
                }
            }
        }

        public Action OnNextPagePerformed { get; set; }
    }
}
